#include <stdio.h>
#include <string.h>
#include <dlfcn.h>

#include "plugin.h"

#define PLUGIN_LIB_PATH "../lib/libplugin-echo.so"
#define PLUGIN_NAME "echo"
#define PLUGIN_NAME_PREFIX "__g_aiops_plugin_"

int main(int argc, char **argv) {
    int ret = -1;
    char plugin_name[128] = { 0 };

    plugin *plg = NULL;
    void *cfg = NULL;
    void *echo = NULL;

    void *handle = dlopen(PLUGIN_LIB_PATH, RTLD_LAZY | RTLD_LOCAL | RTLD_DEEPBIND);
    if (!handle) {
        fprintf(stderr, "Failed open plugin from path: %s\n", PLUGIN_LIB_PATH);
        goto err;
    }

    int prefix_len = strlen(PLUGIN_NAME_PREFIX);
    strncpy(plugin_name, PLUGIN_NAME_PREFIX, prefix_len);
    strncpy(plugin_name + prefix_len, PLUGIN_NAME, strlen(PLUGIN_NAME) + 1);
    plg = dlsym(handle, plugin_name);

    if (!plg) {
        fprintf(stderr, "Failed lookup plugin: %s\n", plugin_name);
        goto err;
    }

    plg->name = plugin_name;
    plg->path = PLUGIN_LIB_PATH;
    plg->handler = handle;

    cfg = plg->load("echo cfg_path");
    if (!cfg) {
        fprintf(stderr, "Failed load plugin cfg\n");
        goto err;
    }

    echo = plg->new(cfg, "plugin echo's param");
    if (!echo) {
        fprintf(stderr, "Failed new plugin instance\n");
        goto err;
    }

    plg->process(echo, "[ PROCESS ] %d %d %d %s\n", 1, 2, 3, "test");

    ret = 0;
err:
    if (plg) {
        if (plg->delete && echo) {
            plg->delete(echo);
        }
        echo = NULL;

        if (plg->unload && cfg) {
            plg->unload(cfg);
        }
        cfg = NULL;
    }

    return ret;
}
